#!/usr/bin/perl
# 2013/09/26 Extract the high associating combination of HindIII

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [map file] -o [list of high associated combinations]\n";
}

my %opt;
getopts("i:o:", \%opt);
my $FILE_map = $opt{i};
my $FILE_out = $opt{o};


my %association;
my %information;
# id chr1 loc1 direction1 quality1 hind1 hiv 2nd_loc1 chr2 loc2 direction2 quality2 hind2 hind_loc2 type(unique or repeat) number(alignable locations) locations
my $fh_map = IO::File->new($FILE_map) or die "cannot open $FILE_map: $!";
while($_ = $fh_map->getline()){
	s/\r?\n//;
	my ($id, $chr1, $loc1, $direction1, $mapQ1, $hinID1, $hinLoc1, $chr2, $loc2, $direction2, $mapQ2, $hinID2, $hinLoc2, $type, $num, $locations) = split /\t/;

	my $hinNum1 = substr($hinID1, 0, -1);
	my $hinNum2 = substr($hinID2, 0, -1);
	my $side1 = substr($hinID1, -1);
	my $side2 = substr($hinID2, -1);

	# only consider L - L combination
	if($side1 ne 'L' or $side2 ne 'L'){
		next;
	}

	my $distance = 'inter';
	if($chr1 eq $chr2){
		$distance = abs($loc1 - $loc2);
		if($distance < 20000){
			next;
		}
	}

	my $key = "$hinID1\t$hinID2";
	my $out = "$chr1\t$hinID1\t$hinLoc1\t$chr2\t$hinID2\t$hinLoc2\t$distance";
	if($hinNum2 < $hinNum1){
		$key = "$hinID2\t$hinID1";
		$out = "$chr2\t$hinID2\t$hinLoc2\t$chr1\t$hinID1\t$hinLoc1\t$distance";
	}

	$association{$key}++;
	$information{$key} = $out;
}
$fh_map->close();



my $fh_out = IO::File->new($FILE_out, 'w') or die "cannot write $FILE_out: $!";
foreach my $key(sort {$association{$b} <=> $association{$a}} keys %association){
	$fh_out->print("$information{$key}\t$association{$key}\n");
}
$fh_out->close();